import {messages} from "share/common";
import React,{Component} from 'react';
import 'styles/data-center/air-report/air-report.scss';
import AdvanceSearch from 'components/advanced-search';
import AirReportUtil from './air-report-util';
import upImage from 'images/data-center/upred@3x.png';
import downImage from 'images/data-center/downgreen3x.png';
import {Radio, Icon, message, Spin} from 'antd'
import {Chart, Geom, Axis, Tooltip, View, Legend, Coord, Label} from 'bizcharts';
import DataSet from '@antv/data-set';
import AirReportServer from './air-report-server';

class AirReport extends Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      loading2: false,
      loading3: false,
      dataSource:  /*AirReportUtil.getTestData() || */[],
      dataSource2: /*AirReportUtil.getTestData2() ||*/ [],
      dataSource3: /*AirReportUtil.getTestData3() ||*/ [],
      searchForm: AirReportUtil.getSearchForm(),
      baseData: {},
      backRate: 0.0,
      days: 0,
      chartWidth: 846,
      chartWidth2: 550,
      pinedList: [],
      detailTotalType: 'm' // 当季还是当月 m:当月 q:当季
    }
    this.legendItems = [
      { value: messages('finance-7.key7')/*当月金额*/, marker: { symbol: 'square', fill: '#6FA4FF', radius: 5 } },
      { value: messages('finance-7.key8')/*同比金额*/, marker: { symbol: 'square', fill: '#50C0FF', radius: 5 } },
      { value: messages('finance-7.key9')/*同比*/, marker: { symbol: 'hyphen', stroke: '#FC9A28', radius: 5, lineWidth: 3 } },
      { value: messages('finance-7.key10')/*环比*/, marker: { symbol: 'hyphen', stroke: '#32CD91', radius: 5, lineWidth: 3 } },
    ];
    this.legendItems3 = [
      { value: messages('finance-7.key11')/*张数*/, marker: { symbol: 'square', fill: '#6FA4FF', radius: 5 } },
      { value: messages('finance-7.key12')/*平均折扣*/, marker: { symbol: 'hyphen', stroke: '#6FA4FF', radius: 5, lineWidth: 3 } },
    ]
    this.detailType = 'month';
    this.paramsData = {};
    this.isDomestic = 1; // 1 国内  0 国际
    this.isDomesticSupplier = 1; // 1 国内  0 国际
  }

  handleSearch = (values) => {
    let month = [];
    let start = parseInt(values.startMonth);
    let end = parseInt(values.endMonth);
    if(end < start){
      message.error(messages('finance-7.key13')/*结束月份不能小于开始月份*/);
      return;
    }
    for(let i=start;i<=end;i++){
      month.push(i);
    }
    let params = {
      statisticByCompanyList: values.statisticByCompanyList,
      statisticByMonthList: month,
      statisticByYear: values.statisticByYear
    }
    this.paramsData = params;
    AirReportServer(this).getReportBaseData(params).then(res => {
      if(res.data.body){
        this.setState({
          baseData: res.data.body,
          backRate: res.data.body ? res.data.body.domesticRefundRatio : '',
          days: res.data.body.averageDomesticBookingAdvancedDays || ''
        });
      }else{
        this.setState({
          baseData: {},
          backRate: 0.0,
          days: 0,
        })
      }
    });
    this.getReportDetail(params);
    this.getAnalysisSupplierData(params);
    this.getAnalysisData(params);
  }

  getReportDetail = (params) => {
    let type = this.detailType === 'month' ? 'm' : 'q'; // m 月度 q 季度
    AirReportServer(this).getReportDetailData(params, type).then(res => {
      this.setState({
        dataSource: res.data.body ? res.data.body.map(item => {
          if(type === 'q'){
            item.month = item[this.detailType];
          }
          return item;
        }) : [],
      });
    })
  }

  getAnalysisData = (params) => {
    let option = JSON.parse(JSON.stringify(params));
    option.isDomestic = this.isDomestic;
    AirReportServer(this).getDayAnalysisData(option).then(res => {
      this.setState({dataSource3: res.data.body});
    })
  }

   getAnalysisSupplierData = (params) => {
    let option = JSON.parse(JSON.stringify(params));
    option.isDomestic = this.isDomesticSupplier;
    AirReportServer(this).getDayAnalysisSupplierData(option).then(res => {
      this.setState({dataSource2: res.data.body});
    })
  }

  dealSource = (data, fields=['totalFlightPrice', 'yearByYearTotalFlightPrice'], value='value') => {
    const ds = new DataSet();
    ds.setState('type', '');
    const dv = ds.createView().source(data);
    dv.transform({
      type: 'fold',
      fields: fields, // 展开字段集
      key: 'type', // key字段
      value: value, // value字段
    })
      .transform({
        type: 'filter',
        callback: (d) => {
          return d.type !== ds.state.type;
        }
      });
    return dv;
  }

  componentDidMount(){
    this.setState({
      chartWidth: this.chartRef.clientWidth - 56,
      chartWidth2: (this.chartRef2.clientWidth - 12) / 2,
    });
    this.advancedSearchRef.search();
  }

  onChangeRadio = (eve, type) => {
    if(type === 'days' || type === 'backRate'){
      let updateParams = AirReportUtil.onChangeRadio(eve, type, this.state.baseData);
      this.setState(updateParams);
    }
    if(type === 'detail'){
      this.detailType = eve.target.value;
      this.getReportDetail(this.paramsData);
      this.setState({detailTotalType: this.detailType === 'month' ? 'm' : 'q'})
    }
    if(type === 'analysis'){// 提前预订天数分析
      this.isDomestic = eve.target.value;
      this.getAnalysisData(this.paramsData);
    }
    if(type === 'supplier'){ // 承运商分析
      this.isDomesticSupplier = eve.target.value;
      this.getAnalysisSupplierData(this.paramsData);
    }
  }

  onPinedListChange = (pinedList) => {
    this.setState({pinedList});
  }

  render(){
    const {baseData, loading, backRate, days, searchForm, dataSource, dataSource2, dataSource3, chartWidth,
      loading2, loading3, chartWidth2, pinedList, detailTotalType} = this.state;
    return (
      <div className='air-report-box'>
        <div className='search-box'>
          <AdvanceSearch
            tableName='air_report_chart_search'
            onSearch={this.handleSearch}
            title={messages('finance-7.key14')/*机票管理报告*/}
            onRef={ref => this.advancedSearchRef = ref}
            getForm={form => this.advancedSearchFormRef = form}
            searchForm={searchForm}
            pinnedList={pinedList}
            onChangePinnedList={this.onPinedListChange}
            notLoadWhenMount
          />
        </div>
        <Spin spinning={loading}>
          <div className='air-total-box'>
            <div className='total-content'>
              <div className='total-content-one'>
                <div className='air-total-tile'>{messages('finance-7.key15')/*机票总金额*/}</div>
                <div className='air-total-num'>{`${baseData.currency || ''} ${this.filterMoney(baseData.totalFlightTicketPrice, 2, true)}`}</div>
                <div className='air-compare-data'>
                  <RenderCompare
                    name={messages('finance-7.key9')/*同比*/}
                    value={baseData.totalFlightTicketPriceYearOnYearRatio}
                    haveImage={true}
                  />
                  <RenderCompare
                    name={messages('finance-7.key10')/*环比*/}
                    value={baseData.totalFlightTicketPriceMonthOnMonthRatio}
                    haveImage={true}
                  />
                </div>
              </div>
              <div className='total-content-one' style={{borderBottom: 0}}>
                <div className='air-total-tile'>{messages('finance-7.key16')/*国内（经济舱）*/}</div>
                <div className='air-compare-data' style={{marginTop: 12}}>
                  <RenderCompare
                    name={messages('finance-7.key17',{arg1: baseData.currency||'CNY'})/*平均票价（{arg1}）*/}
                    value={this.filterMoney(baseData.averageEconomyClassDomesticPrice, 2, true)}
                  />
                  <RenderCompare name={messages('finance-7.key18')/*机票张数（张）*/} value={baseData.totalEconomyClassDomesticTicketNumber || 0}/>
                </div>
              </div>
              <div className='total-content-one' style={{borderBottom: 0, paddingTop: 0}}>
                <div className='air-total-tile'>{messages('finance-7.key19')/*国际（经济舱）*/}</div>
                <div className='air-compare-data' style={{marginTop: 12}}>
                  <RenderCompare
                    name={messages('finance-7.key17',{arg1: baseData.currency||'CNY'})/*平均票价（{arg1}）*/}
                    value={this.filterMoney(baseData.averageEconomyClassForeignPrice, 2, true)}
                  />
                  <RenderCompare name={messages('finance-7.key18')/*机票张数（张）*/} value={baseData.totalEconomyClassForeignTicketsNumber || 0}/>
                </div>
              </div>
            </div>
            <div className='total-detail-chart' ref={chart => this.chartRef = chart}>
              <div className='chart-detail-title-box'>
                <div className='chart-detail-title'>{messages('finance-7.key20')/*机票逐月消费*/}</div>
                <Radio.Group
                  onChange={(eve)=>{this.onChangeRadio(eve,'detail')}}
                  defaultValue="month"
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value="month">{messages('finance-7.key21')/*月度*/}</Radio.Button>
                  <Radio.Button value="quarter">{messages('finance-7.key22')/*季度*/}</Radio.Button>
                </Radio.Group>
              </div>
              <div className='chart-detail-title-box'>
                <div className='tooltip' style={{textAlign: 'left'}}>{messages('common.amount')/*金额*/}</div>
                <div className='tooltip'>{messages('finance-7.key23')/*比率*/}</div>
              </div>
              <div style={{width: '100%'}}>
                <Chart
                  height={308}
                  width={chartWidth}
                  padding="auto"
                  data={this.dealSource(dataSource)}
                >
                  <Legend
                    custom
                    clickable={false}
                    allowAllCanceled
                    items={this.legendItems}/>
                  <Tooltip />
                  <View data={this.dealSource(dataSource)}>
                    <Axis name='month' />
                    <Axis name='value' />
                    <Geom
                      tooltip={['type*value', (type, value) => { // array
                        let name = type === 'totalFlightPrice' ?
                          detailTotalType === 'm' ? messages('finance-7.key24')/*当月总金额*/ :
                            messages('finance-7.key25')/*当季总金额*/ : messages('finance-7.key8')/*同比金额*/
                        return {
                          name,
                          value: value ? value : value === 0 ? '0' : messages('common.empty.text')/*暂无数据*/
                        }
                      }]}
                      type='interval'
                      position={`month*value`}
                      color={['type', (value) => {
                        if (value === 'totalFlightPrice') {
                          return '#6FA4FF';
                        }
                        if (value === 'yearByYearTotalFlightPrice') {
                          return '#50C0FF';
                        }
                      }]}
                      adjust={[{
                        type: 'dodge',
                        marginRatio: 1 / 5,
                      }]}
                    />
                  </View>
                  <View data={this.dealSource(dataSource, ['monthByMonthTotalFlightPriceRatio', 'yearByYearTotalFlightPriceRatio'], 'rate')}>
                    <Axis name='rate' position='right' label={
                      {
                        formatter(text, item, index){
                          return `${text || 0}%`;
                        }
                      }
                    }/>
                    <Geom
                      tooltip={['type*rate', (type, value) => { // array
                        let name = type === 'monthByMonthTotalFlightPriceRatio' ? messages('finance-7.key10')/*环比*/ : messages('finance-7.key9')/*同比*/
                        return {
                          name,
                          value: value ? value+'%' : value === 0 ? '0%' : messages('common.empty.text')/*暂无数据*/
                        }
                      }]}
                      type='line'
                      position={`month*rate`}
                      color={['type', (value) => {
                        if (value === 'monthByMonthTotalFlightPriceRatio') {
                          return '#32CD91';
                        }
                        if (value === 'yearByYearTotalFlightPriceRatio') {
                          return '#FC9A28';
                        }
                      }]}
                      adjust={[{
                        type: 'dodge',
                        marginRatio: 0,
                      }]}
                    />
                    <Geom
                      tooltip={['type*rate', (type, value) => { // array
                        let name = type === 'monthByMonthTotalFlightPriceRatio' ? messages('finance-7.key10')/*环比*/ : messages('finance-7.key9')/*同比*/
                        return {
                          name,
                          value: value ? value+'%' : value === 0 ? '0%' : messages('common.empty.text')/*暂无数据*/
                        }
                      }]}
                      type='point'
                      position={`month*rate`}
                      color={['type', (value) => {
                        if (value === 'monthByMonthTotalFlightPriceRatio') {
                          return '#32CD91';
                        }
                        if (value === 'yearByYearTotalFlightPriceRatio') {
                          return '#FC9A28';
                        }
                      }]}
                      adjust={[{
                        type: 'dodge',
                        marginRatio: 0,
                      }]}
                    />
                  </View>
                </Chart>
              </div>
            </div>
          </div>
        </Spin>
        <div className='air-quota'>
          <div className='total-content-one'>
            <div className='air-total-tile'>{messages('finance-7.key26')/*机票指标*/}</div>
            <div style={{display: 'flex'}}>
              <RenderQuota name={messages('finance-7.key27')/*国内平均折扣（经济舱）*/} value={baseData.averageEconomyClassDomesticDiscount}/>
              <RenderQuota name={messages('finance-7.key28')/*国内全价票比例*/} value={baseData.fullPriceTicketsRatio} num={1}/>
              <RenderQuota
                name={messages('finance-7.key29')/*提前预定天数*/}
                value={days}
                num={1}
                isRadio
                onChangeRadio={(eve)=>this.onChangeRadio(eve, 'days')}
              />
              <RenderQuota
                onChangeRadio={(eve)=>this.onChangeRadio(eve, 'backRate')}
                name={messages('finance-7.key30')/*退票率*/}
                value={backRate}
                num={1}
                isRadio
              />
            </div>
          </div>
        </div>
        <div className='air-supplier-box' ref={chart => this.chartRef2 = chart}>
          <Spin spinning={loading2}>
            <div className='supplier-one' style={{width: chartWidth2+12}}>
              <div className='chart-detail-title-box'>
                <div className='chart-detail-title'>{messages('finance-7.key31')/*承运商分析*/}</div>
                <Radio.Group
                  onChange={(eve)=>{this.onChangeRadio(eve,'supplier')}}
                  defaultValue={1}
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value={1}>{messages('finance-7.key32')/*国内*/}</Radio.Button>
                  <Radio.Button value={0}>{messages('finance-7.key33')/*国际*/}</Radio.Button>
                </Radio.Group>
              </div>
              <Chart
                style={{paddingLeft: '9.5%'}}
                data={dataSource2}
                forceFit
                padding="auto"
                height={344}>
                <Coord type="theta" radius={0.75}/>
                <Axis name='ticketNumberRatio'/>
                <Legend position="left-center"/>
                <Tooltip showTitle={false} />
                <Geom
                  style={{
                    lineWidth: 2,
                    stroke: '#fff',
                  }}
                  tooltip={[
                    "carrierName*totalTicketNumber*totalFarePrice*ticketNumberRatio*currency",
                    (carrierName, totalTicketNumber, totalFarePrice, ticketNumberRatio, currency) => {

                      return {
                        name: carrierName,
                        value: `<div>${messages('finance-7.key34')/*张数占比*/}: ${ticketNumberRatio}%
                                <div>${messages('finance-7.key35')/*机票张数*/}: ${totalTicketNumber}</div>
                                <div>${messages('finance-7.key36')/*票面总额*/}: ${currency} ${totalFarePrice}</div>
                             </div>`
                      };
                    }
                  ]}
                  type="intervalStack"
                  position="ticketNumberRatio"
                  color="carrierName">
                  <Label
                    content="ticketNumberRatio"
                    offset={-40}
                    formatter={(val) => {
                      return val+'%';
                    }}
                  />
                </Geom>
              </Chart>
              {
                dataSource2.length <= 0 && (
                  <div className='no-have-data' style={{position: 'absolute', top: 200, left: '40%'}}>
                    <Icon className='img-icon' type="folder-open" />
                    {messages('common.empty.text')/*暂无数据*/}
                  </div>
                )
              }
            </div>
          </Spin>
          <Spin spinning={loading3}>
            <div className='supplier-two' style={{width: chartWidth2}}>
              <div className='chart-detail-title-box'>
                <div className='chart-detail-title'>{messages('finance-7.key37')/*提前预定天数分析*/}</div>
                <Radio.Group
                  onChange={(eve)=>{this.onChangeRadio(eve,'analysis')}}
                  defaultValue={1}
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value={1}>{messages('finance-7.key32')/*国内*/}</Radio.Button>
                  <Radio.Button value={0}>{messages('finance-7.key33')/*国际*/}</Radio.Button>
                </Radio.Group>
              </div>
              <div className='chart-detail-title-box'>
                <div className='tooltip' style={{textAlign: 'left'}}>{messages('finance-7.key11')/*张数*/}</div>
                <div className='tooltip'>{messages('finance-7.key12')/*平均折扣*/}</div>
              </div>
              <Chart
                padding='auto'
                data={dataSource3}
                forceFit
                scale={{
                  totalFlightTicketNumber: {alias: messages('finance-7.key11')/*张数*/},
                  averageDiscount: {alias: messages('finance-7.key12')/*平均折扣*/}
                }}
                height={314}>
                <Axis name='daysOfBookingAdvanced'/>
                <Axis name='totalFlightTicketNumber' position='left'/>
                <Axis name='averageDiscount' position='right'/>
                <Legend
                  custom
                  clickable={false}
                  allowAllCanceled
                  position='bottom-center'
                  items={this.legendItems3}/>
                <Tooltip/>
                <Geom
                  type='interval'
                  tooltip={[
                    "daysOfBookingAdvanced*statisticDate*totalFlightTicketNumber*ticketsNumberRatio*fullFareTicketRatio*averageDiscount*averageFarePrice*currency",
                    (daysOfBookingAdvanced, statisticDate, totalFlightTicketNumber, ticketsNumberRatio, fullFareTicketRatio, averageDiscount, averageFarePrice, currency) => {

                      return {
                        name: '',
                        value: `<div>${statisticDate}
                                  <div>${messages('finance-7.key38',{arg1: daysOfBookingAdvanced})/*提前预订天数：{arg1}*/}</div>
                                  <div>${messages('finance-7.key39',{arg1: totalFlightTicketNumber})/*张数：{arg1}*/}</div>
                                  <div>${messages('finance-7.key40',{arg1: ticketsNumberRatio})/*张数占比：{arg1}*/}%</div>
                                  <div>${messages('finance-7.key41',{arg1: fullFareTicketRatio})/*全票价比例：{arg1}*/}%</div>
                                  <div>${messages('finance-7.key42',{arg1: averageDiscount})/*平均折扣：{arg1}*/}</div>
                                  <div>${messages('finance-7.key43',{arg1: currency,arg2: averageFarePrice})/*平均票面价：{arg1} {arg2}*/}</div>
                             </div>`
                      };
                    }
                  ]}
                  position='daysOfBookingAdvanced*totalFlightTicketNumber'/>
                <Geom
                  tooltip={[]}
                  type='line'
                  position='daysOfBookingAdvanced*averageDiscount'
                />
                <Geom
                  tooltip={[
                    "daysOfBookingAdvanced*averageDiscount",
                    (daysOfBookingAdvanced, averageDiscount) => {
                      return {
                        name: messages('finance-7.key12')/*平均折扣*/,
                        value: averageDiscount
                      }
                    }
                  ]}
                  type='point'
                  position='daysOfBookingAdvanced*averageDiscount'
                />
              </Chart>
            </div>
          </Spin>
        </div>

      </div>
    )
  }
}

const RenderCompare = function({name, value, haveImage}){
  let imgUrl = haveImage && value ? value > -1 ? upImage : downImage : '';
  if(haveImage){
    value = `${value || 0}%`;
  }
  return (
    <div className='tong-compare'>
      <div className='tong-font'>{name}</div>
      <div className='tong-num'>
        {value}
        {imgUrl && <img className='tip-image-size' src={imgUrl}/>}
      </div>
    </div>
  )
}
const RenderQuota = function({name, value, num, isRadio, onChangeRadio}){
  let sty = {marginTop: 12, width: '25%', borderRight: '1px solid #ebf0f4'};
  if(num && num > 0){
    sty.paddingLeft = 20;
  }
  if(!value){
    value = (
      <div className='no-have-data'>
        <Icon className='img-icon' type="folder-open" />
        {messages('common.empty.text')/*暂无数据*/}
      </div>
    )
  }
  return (
    <div className='air-compare-data' style={sty}>
      <div className='tong-compare'>
        <div className='tong-font'>
          {name}
          {
            isRadio && (
              <Radio.Group
                onChange={(eve)=>{onChangeRadio && onChangeRadio(eve)}}
                defaultValue="in"
                buttonStyle="solid"
                size="small"
              >
                <Radio.Button value="in">{messages('finance-7.key32')/*国内*/}</Radio.Button>
                <Radio.Button value="out">{messages('finance-7.key33')/*国际*/}</Radio.Button>
              </Radio.Group>
            )
          }
        </div>
        <div className='air-total-num' style={{lineHeight: '40px', marginTop: 4}}>
          {value}
        </div>
      </div>
    </div>
  )
}

export default AirReport;
